package com.sky.cqculture.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.cqculture.Mapper.ProductMapper;
import com.sky.cqculture.Mapper.CategoryMapper;
import com.sky.cqculture.pojo.Category;
import com.sky.cqculture.pojo.Product;
import com.sky.cqculture.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private CategoryMapper categoryMapper;
    
    @Override
    public Product findProductById(Integer id) {
        Product product = productMapper.findById(id);
        if (product != null && product.getCategoryId() != null) {
            Category category = categoryMapper.findById(product.getCategoryId());
            if (category != null) {
                product.setCategoryName(category.getName());
            }
        }
        return product;
    }
    
    @Override
    public List<Product> findProductsByCategoryId(Integer categoryId) {
        List<Product> products = productMapper.findByCondition(categoryId, "default");
        // 设置分类名称
        setCategoryNames(products);
        return products;
    }
    
    @Override
    public List<Product> getPopularProducts(Integer limit) {
        List<Product> products = productMapper.findPopularProducts(limit);
        // 设置分类名称
        setCategoryNames(products);
        return products;
    }
    
    @Override
    public PageInfo<Product> findProductsByPage(Integer categoryId, String sortType, Integer pageNum, Integer pageSize) {
        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        
        // 查询数据
        List<Product> products = productMapper.findByCondition(categoryId, sortType);
        
        // 设置分类名称
        setCategoryNames(products);
        
        // 封装为PageInfo对象
        return new PageInfo<>(products);
    }
    
    // 辅助方法：为商品列表设置分类名称
    private void setCategoryNames(List<Product> products) {
        if (products != null && !products.isEmpty()) {
            for (Product product : products) {
                if (product.getCategoryId() != null) {
                    Category category = categoryMapper.findById(product.getCategoryId());
                    if (category != null) {
                        product.setCategoryName(category.getName());
                    }
                }
            }
        }
    }
}